﻿using EMoney.IStock.Client.Business;
using EMoney.IStock.Client.Business.MC;
using EMoney.IStock.Client.Framework;
using EMoney.IStock.Client.Models.MC;
using System;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Linq.Dynamic;
using EMoney.IStock.Client.Core;
using EMoney.IStock.Client.Business.Cpyx;

namespace EMoney.IStock.Client.Web.Controllers
{
    public class MCController : Controller
    {
        /// <summary>
        /// 会员中心
        /// </summary>
        /// <returns></returns>
        public ActionResult index()
        {
            //需要定位到的标签页
            string tab=Request["id"];

            int userid = 0;
            if (!string.IsNullOrEmpty(Request["token"]))    //token有值时，执行认证操作
            {
                userid = TokenBll.GetUserIDByToken(Request["token"]);
            }
            else
            {
                userid = TokenBll.GetUserIDByCookie();  //从Cookie中获取用户编号
            }

            if (userid == 0)
            {
                return null;
            }

            MyInfoBll myInfoBll = new MyInfoBll();

            ViewBag.MyInfo = myInfoBll.GetMyInfo(userid, true);   //个人信息

            List<UserPic> userPicList = myInfoBll.GetUserPicList(); //用户头像列表

            if (userPicList != null && userPicList.Count > 0)
            {
                ViewBag.UserPicList = userPicList.FindAll(lst => lst.Size == 77);
            }

            TipsInfoBll tipsInfoBll = new TipsInfoBll();

            ViewBag.tab = tab;

            ViewBag.TipsInfoList = tipsInfoBll.GetTipsInfoList();   //Tips信息

            return View();
        }

        /// <summary>
        /// 我的首页
        /// </summary>
        /// <returns></returns>
        public ActionResult home()
        {
            return View();
        }

        /// <summary>
        /// 抽奖活动奖品中心
        /// </summary>
        /// <returns></returns>
        public ActionResult jp()
        {
            //先获取用户所有的中奖记录
            int userid = TokenBll.GetUserIDByCookie();

            CJBLL cjbll = new CJBLL();
            DataTable logtb = cjbll.SelectUserLog(userid.ToString());//userid.ToString()

            ViewBag.log = logtb;
            return View();
        }

        /// <summary>
        /// 任务页
        /// </summary>
        /// <returns></returns>
        public ActionResult task()
        {
            return View();
        }

        /// <summary>
        /// 特权
        /// </summary>
        public ActionResult privilege()
        {
            return View();
        }

        /// <summary>
        /// 增值权限
        /// </summary>
        /// <returns></returns>
        public ActionResult rights()
        {
            int userid = TokenBll.GetUserIDByCookie();  //从Cookie中获取用户编号

            if (userid == 0)
            {
                return null;
            }

            return View();
        }

        /// <summary>
        /// 任务进度提示
        /// </summary>
        /// <returns></returns>
        public ActionResult tasktips()
        {
            int userid = TokenBll.GetUserIDByCookie();  //从Cookie中获取用户编号

            if (userid == 0)
            {
                return null;
            }

            MyInfoBll myInfoBll = new MyInfoBll();
            TaskInfoBll taskInfoBll = new TaskInfoBll();

            MC_MyInfo myInfo = myInfoBll.GetMyInfo(userid);

            if (myInfo != null)
            {
                int todayCount = 0;
                int todayINum = 0;
                
                taskInfoBll.GetTodayCompletedCountAndINum(myInfo, out todayCount, out todayINum);    //获取用户今日完成的任务数量及获得的i豆数量
                
                ViewBag.TodayCount = todayCount;
                ViewBag.TodayINum = todayINum;

                List<MC_TaskInfo> unCompletedTaskInfoList = taskInfoBll.GetUserTaskInfoList(myInfo, 0);   //未完成的任务信息列表
                
                if (unCompletedTaskInfoList != null && unCompletedTaskInfoList.Count > 0)
                {
                    ViewBag.UnCount = unCompletedTaskInfoList.Count;

                    int unTotalINum = 0;
                    foreach (MC_TaskInfo taskInfo in unCompletedTaskInfoList)
                    {
                        unTotalINum += taskInfo.iNum;
                    }

                    ViewBag.UnINum = unTotalINum;
                }
            }

            return View();
        }

        /// <summary>
        /// 更换头像
        /// </summary>
        /// <returns></returns>
        public string cp()
        {
            int userid = TokenBll.GetUserIDByCookie();  //从Cookie中获取用户编号

            if (userid == 0)
            {
                return string.Empty;
            }

            string reqPic = Request["p"];

            if (string.IsNullOrEmpty(reqPic))
            {
                return string.Empty;
            }
            else
            {
                MyInfoBll myInfoBll = new MyInfoBll();

                return myInfoBll.UpdateUserPic(userid, reqPic);
            }
        }

        /// <summary>
        /// 改变昵称
        /// </summary>
        /// <returns></returns>
        public string cn()
        {
            int userid = TokenBll.GetUserIDByCookie();  //从Cookie中获取用户编号

            if (userid == 0)
            {
                return string.Empty;
            }

            string reqNick = Request["nick"];

            if (string.IsNullOrEmpty(reqNick))
            {
                return string.Empty;
            }
            else
            {
                reqNick = Server.UrlDecode(reqNick);

                MyInfoBll myInfoBll = new MyInfoBll();

                return myInfoBll.UpdateUserName(userid, reqNick);
            }
        }

        /// <summary>
        /// 绑定账号
        /// </summary>
        /// <returns></returns>
        public string bind()
        {
            int userid = TokenBll.GetUserIDByCookie();  //从Cookie中获取用户编号

            if (userid == 0)
            {
                return string.Empty;
            }

            string ret = string.Empty;
            string reqFlag = Request["flag"];
            string reqAccount = Request["account"];
            string reqPwd = Request["pwd"];
            string reqCode = Request["code"];
            string reqLoginType = Request["logintype"];

            if (reqLoginType == "1" && string.IsNullOrEmpty(reqPwd))
            {
                reqPwd = "0";
            }

            if (!string.IsNullOrEmpty(reqFlag) && !string.IsNullOrEmpty(reqAccount) 
                && !string.IsNullOrEmpty(reqPwd) && !string.IsNullOrEmpty(reqCode))
            {
                reqAccount = EncryptionUtil.Decrypt(reqAccount);

                if (reqPwd != "0")
                {
                    reqPwd = EncryptionUtil.Decrypt(reqPwd);
                }

                if (!string.IsNullOrEmpty(reqAccount) && !string.IsNullOrEmpty(reqPwd))
                {
                    string cacheCode = SendBll.GetCode(reqAccount);

                    if (string.IsNullOrEmpty(cacheCode))
                    {
                        ret = "验证码已失效，请获取";
                    }
                    else
                    {
                        if (reqCode != cacheCode)
                        {
                            ret = "验证码错误";
                        }
                        else
                        {
                            string type = "0";
                            switch (reqFlag)
                            {
                                case "email":
                                    type = "1";
                                    break;
                                default:
                                    break;
                            }
                            
                            MyInfoBll myInfoBll = new MyInfoBll();

                            ret = myInfoBll.BindMapUser(userid, reqAccount, type, reqPwd);
                        }
                    }
                }
            }

            return ret;
        }

        /// <summary>
        /// 发送手机或短信验证码
        /// </summary>
        /// <returns></returns>
        public string send()
        {
            int userid = TokenBll.GetUserIDByCookie();  //从Cookie中获取用户编号

            if (userid == 0)
            {
                return string.Empty;
            }

            string ret = string.Empty;
            string reqFlag = Request["flag"];
            string reqAccount = Request["account"];
            string reqAssociatedLogin = Request["associatedLogin"];

            if (!string.IsNullOrEmpty(reqFlag) && !string.IsNullOrEmpty(reqAccount))
            {
                reqAccount = EncryptionUtil.Decrypt(reqAccount);

                if (!string.IsNullOrEmpty(reqAccount))
                {
                    bool isExist = WebApiBll.IsExistUser(reqAccount, reqFlag == "mobile" ? "1" : "2");

                    if (isExist)    //账号已存在
                    {
                        //switch (reqFlag)
                        //{
                        //    case "mobile":
                        //        return "手机号码已存在";
                        //    case "email":
                        //        return "邮箱账号已存在";
                        //    default:
                        //        break;
                        //}

                        //return "账号已存在";
                        ret = "2";
                    }

                    string code = string.Empty;
                    string cacheCode = SendBll.GetCode(reqAccount); //获取该账号有效期内发送的验证码

                    if (ConfigHelper.IsOnline == "0")
                    {
                        code = "123456";
                    }
                    else
                    {
                        if (string.IsNullOrEmpty(cacheCode))
                        {
                            code = new Random().Next(100000, 999999).ToString();
                        }
                        else
                        {
                            code = cacheCode;
                        }
                    }

                    switch (reqFlag)
                    {
                        case "mobile":

                            if (SendBll.SendSms(userid.ToString(), reqAccount, string.Concat("您的验证码是:", code, "（30分钟内有效），请将该验证码填写到页面的对应位置")))
                            {
                                SendBll.CacheCode(reqAccount, code);
                                ret += "1";
                            }
                            else
                            {
                                ret = "0";
                            }
                            break;
                        case "email":
                            string subject = string.Concat("爱炒股用户邮件验证码:", code);
                            string body = "<strong>尊敬的爱炒股用户</strong>:<br /><p><span style='white-space:pre'>	</span>&nbsp;&nbsp;你的验证码为：<strong>" + code + "&nbsp;</strong>（30分钟内有效），请将验证码填写到页面中的指定位置。 <br /><span style='white-space:pre'>	</span>&nbsp;&nbsp;感谢你使用益盟爱炒股软件！如果你不是爱炒股用户，请你忽略本邮件，给你带来的不便，我们深表歉意。（该邮件不需要回复）</p><p><span style='white-space:pre'></span><strong>益盟爱炒股</strong></p>";

                            if (SendBll.SendEmail(userid.ToString(), reqAccount, subject, body))
                            {
                                SendBll.CacheCode(reqAccount, code);
                                ret += "1";
                            }
                            else
                            {
                                ret = "0";
                            }
                            break;
                        default:
                            break;
                    }

                    if (ret == "1" || ret == "21")  //验证码发送成功，验证当前用户是否输入存在登录密码
                    {
                        MyInfoBll myInfoBll = new MyInfoBll();

                        OneUserInfo oneUserInfo = myInfoBll.GetOneUserInfo(userid.ToString());

                        if (oneUserInfo != null && oneUserInfo.pwd == 1)
                        {
                            ret = "2";
                        }
                    }
                }
            }

            return ret;
        }

        /// <summary>
        /// 获取任务列表（已完成或未完成）
        /// </summary>
        /// <returns></returns>
        public string tasklist()
        {
            int userid = TokenBll.GetUserIDByCookie();  //从Cookie中获取用户编号

            if (userid == 0)
            {
                return string.Empty;
            }

            string ret = string.Empty;
            string reqFlag = Request["flag"];

            if (!string.IsNullOrEmpty(reqFlag))
            {
                MyInfoBll myInfoBll = new MyInfoBll();
                TaskInfoBll taskInfoBll = new TaskInfoBll();

                MC_MyInfo myInfo = myInfoBll.GetMyInfo(userid);

                if (myInfo != null)
                {
                    List<MC_TaskInfo> taskInfoList = null;

                    switch (reqFlag)
                    {
                        case "1":   //已完成
                            taskInfoList = taskInfoBll.GetUserTaskInfoList(myInfo, 1);
                            break;
                        case "0":   //未完成
                            taskInfoList = taskInfoBll.GetUserTaskInfoList(myInfo, 0);
                            break;
                        default:
                            break;
                    }

                    if (taskInfoList != null && taskInfoList.Count > 0)
                    {
                        switch (reqFlag)
                        {
                            case "1":   //已完成 (按完成日期、时间降序)
                                taskInfoList = taskInfoList.AsQueryable().OrderBy("CompletedTime desc").ToList();
                                break;
                            case "0":   //未完成 (优先显示一次性任务；按奖励i豆数量降序)
                                taskInfoList = taskInfoList.AsQueryable().OrderBy("Type asc,iNum desc").ToList();
                                break;
                            default:
                                break;
                        }

                        ret = JsonHelper.ToJson(taskInfoList);
                    }
                }
            }

            return ret;
        }

        /// <summary>
        /// 完成任务
        /// </summary>
        /// <returns></returns>
        public string ct()
        {
            int userid = TokenBll.GetUserIDByCookie();  //从Cookie中获取用户编号

            if (userid == 0)
            {
                return string.Empty;
            }

            string ret = string.Empty;

            try
            {
                string reqTaskID = Request["tid"];

                if (!string.IsNullOrEmpty(reqTaskID))
                {
                    if (!string.IsNullOrEmpty(reqTaskID))
                    {
                        int taskID = 0;

                        if (int.TryParse(reqTaskID, out taskID))
                        {
                            MyInfoBll myInfoBll = new MyInfoBll();

                            MC_MyInfo myInfo = myInfoBll.GetMyInfo(userid);

                            if (myInfo != null)
                            {
                                bool complete = false;
                                MC_TaskID mc_TaskID = (MC_TaskID)taskID;

                                switch (mc_TaskID)
                                {
                                    case MC_TaskID.ContinueLogin:
                                    case MC_TaskID.HalfHour:
                                    case MC_TaskID.OneHour:
                                    case MC_TaskID.TowHours:
                                        //连续登录、在线半小时、在线一小时、在线两小时 不通过此接口完成
                                        break;
                                    case MC_TaskID.KContinueGame:
                                    case MC_TaskID.kGameCount:
                                        KGameTaskBll kGameTaskBll = new KGameTaskBll();

                                        if (mc_TaskID == MC_TaskID.KContinueGame)
                                        {
                                            complete = kGameTaskBll.CompleteKContinueGameTask(myInfo);  //完成连续参加K线英雄游戏任务
                                        }
                                        else if (mc_TaskID == MC_TaskID.kGameCount)
                                        {
                                            complete = kGameTaskBll.CompleteKGameCountTask(myInfo);  //完成收益≥10%的局数任务
                                        }
                                        break;
                                    default:
                                        TaskInfoBll taskInfoBll = new TaskInfoBll();

                                        complete = taskInfoBll.CompleteTask(myInfo, taskID);   //完成任务
                                        break;
                                }

                                if (complete)
                                {
                                    ret = JsonHelper.ToJson(myInfo);
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogManager.DefaultLogger.Error(ex, "ct完成任务失败");
            }

            return ret;
        }

        /// <summary>
        /// 连登任务完成提示
        /// </summary>
        public void cl()
        {
            int userid = TokenBll.GetUserIDByCookie();  //从Cookie中获取用户编号

            if (userid != 0)
            {
                MyInfoBll myInfoBll = new MyInfoBll();

                MC_MyInfo myInfo = myInfoBll.GetMyInfo(userid);

                if (myInfo != null)
                {
                    myInfo.ContinueLoginTips = "1";

                    myInfoBll.SetMyInfo(myInfo);
                }
            }
        }

        /// <summary>
        /// 在线时长
        /// </summary>
        /// <returns></returns>
        public string ot()
        {
            string ret = string.Empty;
            int userid = TokenBll.GetUserIDByCookie();  //从Cookie中获取用户编号

            if (userid != 0)
            {
                OnlineTimeBll onlineTimeBll = new OnlineTimeBll();

                ret = onlineTimeBll.CompleteOnlineTimeTask(userid);
            }

            return ret;
        }
    }
}
